package com.ruoyi.web.controller.module.active;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.RegexUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.active.CommunityActive;
import com.ruoyi.system.domain.module.estate.EstateRoom;
import com.ruoyi.system.service.module.active.ICommunityActiveService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.web.controller.common.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 社区活动Controller
 *
 * @author ruoyi
 * @date 2023-12-26
 */
@Validated
@Api(value = "社区活动控制器", tags = {"社区活动管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/active")
public class CommunityActiveController extends BaseController {

    private final ICommunityActiveService communityActiveService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
	@Value("${ruoyi.profile}")
	private String uploadPath;

    /**
     * 查询社区活动列表
     */
    @ApiOperation("查询社区活动列表")
    @PreAuthorize("@ss.hasPermi('module:active:list')")
    @GetMapping("/list")
    public TableDataInfo<CommunityActive> list(@Validated CommunityActive communityActive) {
        QueryWrapper<CommunityActive> qw = new QueryWrapper<>();
		if(StrUtil.isNotEmpty(communityActive.getActiveTitle())){
			qw.like("active_title", communityActive.getActiveTitle());
		}
		if(communityActive.getActiveType() != null){
			qw.eq("active_type", communityActive.getActiveType());
		}
		qw.orderByDesc("id");

        TableDataInfo<CommunityActive> td = PageUtils.buildDataInfo(communityActiveService.page(PageUtils.buildPage(),qw));
        List<CommunityActive> list = td.getRows();
		if(CollUtil.isNotEmpty(list)){
			for (CommunityActive active : list){
				if(StrUtil.isNotEmpty(active.getPreviewImg())){
					active.setPreviewImgPath(imgUrl + active.getPreviewImg());
				}
				if(StrUtil.isNotEmpty(active.getQrCode())){
					active.setQrCode(imgUrl + active.getQrCode());
				}
			}
		}
        return td;
    }

    /**
     * 导出社区活动列表
     */
    @ApiOperation("导出社区活动列表")
    @PreAuthorize("@ss.hasPermi('module:active:export')")
    @Log(title = "社区活动", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<CommunityActive> export(@Validated CommunityActive communityActive) {
        List<CommunityActive> list = communityActiveService.list();
        ExcelUtil<CommunityActive> util = new ExcelUtil<>(CommunityActive.class);
        return util.exportExcel(list, "社区活动");
    }

    /**
     * 获取社区活动详细信息
     */
    @ApiOperation("获取社区活动详细信息")
    @PreAuthorize("@ss.hasPermi('module:active:query')")
    @GetMapping("/{id}")
    public AjaxResult<CommunityActive> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        CommunityActive active = communityActiveService.getById(id);
		if(active!= null){
			if(StrUtil.isNotEmpty(active.getPreviewImg())){
				active.setPreviewImgPath(imgUrl + active.getPreviewImg());
			}
		}
        return AjaxResult.success(active);
    }

	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:estate:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody CommunityActive communityActive) {
		if (communityActive.getId() != null) {
			try {
				communityActive = communityActiveService.getById(communityActive.getId());
				String fileName = "communityActive_qr_" + communityActive.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/active/info?id=" + communityActive.getId();
//				pagesProperty/pages/active/detail/index
				int upload_type = FileUploadUtils.TYPE_COMMUNITY_ACTIVE;
				System.out.println("content:  " + content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + communityActive.getId() + "/" + fileName;

				QRCodeUtilEx.createQrCodeImg(content, communityActive.getActiveTitle(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				communityActive.setQrCode(img_key);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (communityActiveService.updateById(communityActive)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}

		/**
		 * 新增社区活动
		 */
    @ApiOperation("新增社区活动")
    @PreAuthorize("@ss.hasPermi('module:active:add')")
    @Log(title = "社区活动", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody CommunityActive communityActive) {
		if(StrUtil.isNotEmpty(communityActive.getActiveContent())){
			communityActive.setActiveContent(RegexUtil.convertProductDescription(communityActive.getActiveContent()));
		}
        Boolean p = communityActiveService.save(communityActive);
		if (communityActive.getId() != null) {
			try {
				communityActive = communityActiveService.getById(communityActive.getId());
				String fileName = "communityActive_qr_" + communityActive.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/room/info?id=" + communityActive.getId();
//				pagesProperty/pages/active/detail/index
				int upload_type = FileUploadUtils.TYPE_COMMUNITY_ACTIVE;
				System.out.println("content:  " + content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + communityActive.getId() + "/" + fileName;

				QRCodeUtilEx.createQrCodeImg(content, communityActive.getActiveTitle(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				communityActive.setQrCode(img_key);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (communityActiveService.updateById(communityActive)) {
				return AjaxResult.success();
			}
		}
        return toAjax(p);
    }

    /**
     * 修改社区活动
     */
    @ApiOperation("修改社区活动")
    @PreAuthorize("@ss.hasPermi('module:active:edit')")
    @Log(title = "社区活动", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody CommunityActive communityActive) {
		if(StrUtil.isNotEmpty(communityActive.getActiveContent())){
			communityActive.setActiveContent(RegexUtil.convertProductDescription(communityActive.getActiveContent()));
		}
        return toAjax(communityActiveService.updateById(communityActive) ? 1 : 0);
    }

    /**
     * 删除社区活动
     */
    @ApiOperation("删除社区活动")
    @PreAuthorize("@ss.hasPermi('module:active:remove')")
    @Log(title = "社区活动" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(communityActiveService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
